package com.yuba.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuba.common.core.constant.ActionTypes;
import com.yuba.common.core.domain.model.MessageMeta;
import com.yuba.common.core.exception.front.CollectException;
import com.yuba.common.core.utils.MapstructUtils;
import com.yuba.common.core.utils.SpringUtils;
import com.yuba.common.mybatis.core.page.PageQuery;
import com.yuba.common.mybatis.core.page.TableDataInfo;
import com.yuba.common.satoken.utils.LoginHelper;
import com.yuba.front.domain.CollectPosts;
import com.yuba.front.domain.bo.CollectPostsBo;
import com.yuba.front.domain.vo.CollectPostsVo;
import com.yuba.front.event.MessageHandleEvent;
import com.yuba.front.event.UnMessageHandleEvent;
import com.yuba.front.event.UpdatePostsEvent;
import com.yuba.front.mapper.CollectPostsMapper;
import com.yuba.front.service.ICollectPostsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 帖子收藏Service业务层处理
 *
 * @author modakai
 * @date 2024-12-07
 */
@RequiredArgsConstructor
@Service
public class CollectPostsServiceImpl implements ICollectPostsService {

    private final CollectPostsMapper baseMapper;

    /**
     * 查询帖子收藏
     *
     * @param collectId 主键
     * @return 帖子收藏
     */
    @Override
    public CollectPostsVo queryById(Long collectId){
        return baseMapper.selectVoById(collectId);
    }

    /**
     * 分页查询帖子收藏列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 帖子收藏分页列表
     */
    @Override
    public TableDataInfo<CollectPostsVo> queryPageList(CollectPostsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CollectPosts> lqw = buildQueryWrapper(bo);
        Page<CollectPostsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的帖子收藏列表
     *
     * @param bo 查询条件
     * @return 帖子收藏列表
     */
    @Override
    public List<CollectPostsVo> queryList(CollectPostsBo bo) {
        LambdaQueryWrapper<CollectPosts> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CollectPosts> buildQueryWrapper(CollectPostsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CollectPosts> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, CollectPosts::getUserId, bo.getUserId());
        lqw.eq(bo.getPostId() != null, CollectPosts::getPostId, bo.getPostId());
        return lqw;
    }

    /**
     * 新增帖子收藏
     *
     * @param bo 帖子收藏
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(CollectPostsBo bo) {
        CollectPosts add = MapstructUtils.convert(bo, CollectPosts.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCollectId(add.getCollectId());
        }
        return flag;
    }

    /**
     * 修改帖子收藏
     *
     * @param bo 帖子收藏
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CollectPostsBo bo) {
        CollectPosts update = MapstructUtils.convert(bo, CollectPosts.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CollectPosts entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除帖子收藏信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void collectPosts(Long postsId, Long userId, Long authorId) {
        CollectPosts collectPosts = new CollectPosts();
        collectPosts.setPostId(postsId);
        collectPosts.setUserId(userId);
        int insert = baseMapper.insert(collectPosts);
        if (insert <= 0) {
            throw new CollectException("front.collect.error");
        }

        if (!userId.equals(authorId)) {
            // 发送点赞帖子消息
            MessageHandleEvent messageEvent = MessageHandleEvent.builder()
                .type(ActionTypes.COLLECT)
                .userId(authorId)
                .senderId(userId)
                .senderNickname(LoginHelper.getLoginUser().getNickname())
                .sourceId(postsId)
                .message("收藏了您的帖子")
                .meta(new MessageMeta()
                    .setType(ActionTypes.POSTS)
                    .setPostsId(postsId)
                )
                .build();
            SpringUtils.context().publishEvent(messageEvent);
        }

        // 修改帖子推荐分
        UpdatePostsEvent event = UpdatePostsEvent.build(postsId, ActionTypes.COLLECT, true);
        SpringUtils.context().publishEvent(event);
    }

    @Override
    public void unCollectPosts(Long postsId, Long authorId, Long userId) {
        LambdaQueryWrapper<CollectPosts> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CollectPosts::getPostId, postsId)
            .eq(CollectPosts::getUserId, userId);
        int delete = baseMapper.delete(lqw);
        if (delete <= 0) {
            throw new CollectException("front.unCollect.error");
        }

        // 修改文章推荐分
        UpdatePostsEvent event = UpdatePostsEvent.build(postsId, ActionTypes.COLLECT, false);
        SpringUtils.context().publishEvent(event);

        if (!userId.equals(authorId)) {
            // 收藏对应的收藏
            UnMessageHandleEvent unMessageHandleEvent = UnMessageHandleEvent.builder()
                .type(ActionTypes.COLLECT)
                .userId(authorId)
                .senderId(userId)
                .sourceId(postsId)
                .meta(new MessageMeta()
                    .setType(ActionTypes.POSTS)
                    .setPostsId(postsId))
                .build();

            SpringUtils.context().publishEvent(unMessageHandleEvent);
        }
    }
}
